<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Todo List</title>
		<link rel="stylesheet" href="/assets/css/base.css">
		<link rel="stylesheet" href="/assets/css/index.css">
		<!-- 进度条 -->
		<link rel="stylesheet" href="/js/nprogress/nprogress.css">
	</head>
	<body>
		<section class="todoapp">
			<header class="header">
				<h1>todos</h1>
				<input class="new-todo" placeholder="What needs to be done?" id="task" autofocus>
			</header>
			<!-- This section should be hidden by default and shown when there are todos -->
			<section class="main">
				<input class="toggle-all" type="checkbox">
				<label for="toggle-all">Mark all as complete</label>
				<ul class="todo-list" id="todo-list"></ul>
			</section>
			<!-- This footer should hidden by default and shown when there are todos -->
			<footer class="footer">
				<!-- This should be `0 items left` by default -->
				<span class="todo-count"><strong id="count">0</strong> item left</span>
				<!-- Remove this if you don't implement routing -->
				<ul class="filters">
					<li>
						<a class="selected" href="javascript:;" id="all">All</a>
					</li>
					<li>
						<a href="javascript:;" id="active">Active</a>
					</li>
					<li>
						<a href="javascript:;" id="completed">Completed</a>
					</li>
				</ul>
				<!-- Hidden if no completed items are left ↓ -->
				<button class="clear-completed" id="clearAll">Clear completed</button>
			</footer>
		</section>
		<script src="/js/jquery.min.js"></script>
		<script src="/js/template-web.js"></script>
		<script src="/js/nprogress/nprogress.js"></script>
		<script type="text/html" id="taskTpl">
			{{each tasks}}
			<li class="{{$value.complete ? 'completed': ''}}">
				<div class="view">
					<input class="toggle" type="checkbox" {{$value.complete ? 'checked': ''}}>
					<label>{{$value.title}}</label>
					<button class="destroy" data-id="{{$value._id}}"></button>
				</div>
				<input class="edit" value="Rule the web">
			</li>
			{{/each}}
		</script>
		<script>
			let taskAry = [];
			const taskBox = $("#todo-list");
			const strong = $("#count");
			const all = $("#all");
			const completed = $("#completed");
			const active = $("#active");
			const clearAll = $("#clearAll");
			$.ajax({
				url: '/todo/task',
				type: 'get',
				success: (response) => {
					taskAry = response;
					render(taskAry);
				}
			})
			const task = $("#task");
			task.on('keyup', function (event) {
				 if(event.keyCode === 13){
					//  回车键
					let taskName = $(this).val();
					if( taskName.trim().length === 0) {
						alert('请输入任务名称')
						return;
					}
					$.ajax({
						url: '/todo/addTask',
						type: 'post',
						data: JSON.stringify({
							title: taskName,
						}),
						contentType: 'application/json',
						success: response => {
							taskAry.push(response);
							render(taskAry);
							task.val('');
						}
					})
				 }
			})
			
			const render = (arr) => {
				const html = template("taskTpl", {
						tasks: arr
					})
					taskBox.html(html);
					accumulate();
			}

			// 删除任务
			taskBox.on('click', '.destroy', function () {
				const id = $(this).attr('data-id');
				$.ajax({
					url: '/todo/deleteTask',
					type: 'get',
					data: {
						id
					},
					success: (response) => {
						if(response === 'ok') {
							// 找到已删除的id
							var index = taskAry.findIndex(item => item._id === id);
							taskAry.splice(index, 1);
							render(taskAry);
						}else {
							alert('删除失败');
						}
					}
				});
			})

			// 勾选
			taskBox.on('change', '.toggle', function () {
				// 代表复选框是否选中，true是选中，false是未选中
				const status = $(this).is(':checked');
				const id = $(this).siblings('button').attr('data-id');
				$.ajax({
					url: '/todo/updateTask',
					type: 'post',
					data: JSON.stringify({
						id,
						complete: status
					}),
					contentType: 'application/json',
					success: (response) => {
						if(response === 'ok') {
							// 修改任务的状态
							var task = taskAry.find(item => item._id === id);
							task.complete = status;
							render(taskAry);
						}else {
							alert('修改失败');
						}
					}
				});
			})

			// 双击
			taskBox.on('dblclick', 'label', function () {
				$(this).parent().parent().addClass('editing');
				$(this).parent().siblings('input').val($(this).text());
				$(this).parent().siblings('input').focus();
			})

			// 当文本框离开焦点
			taskBox.on('blur', '.edit', function () {
				const newTitle = $(this).val();
				const id = $(this).siblings().find('button').attr('data-id');
				$.ajax({
					url: '/todo/modifyTask',
					type: 'post',
					data: JSON.stringify({
						id,
						title: newTitle
					}),
					contentType: 'application/json',
					success: (response) => {
						if(response === 'ok') {
							// 修改任务的状态
							var task = taskAry.find(item => item._id === id);
							task.title = newTitle;
							render(taskAry);
						}else {
							alert('修改失败');
						}
					}
				});
			})
			
			function accumulate() {
				let count = 0;
				// 未完成的数组
				let newAry = taskAry.filter(item => !item.complete);
				count = newAry.length;
				strong.text(count);
			}
			
			all.on('click', function () {
				render(taskAry);
				$(this).addClass('selected').parent().siblings().find('a').removeClass('selected');
			})

			completed.on('click', function () {
				render(taskAry.filter(item => item.complete));
				$(this).addClass('selected').parent().siblings().find('a').removeClass('selected');
			})

			active.on('click', function () {
				render(taskAry.filter(item => !item.complete));
				$(this).addClass('selected').parent().siblings().find('a').removeClass('selected');
			})

			clearAll.on('click', function () {
				if(!confirm('你确认要删除全部已完成的任务吗'))return;
				$.ajax({
					url: '/todo/clearAll',
					success: (response => {
						if(response === 'ok') {
							taskAry = taskAry.filter(item => !item.complete);
							render(taskAry);
						}else {
							alert('操作失败');
						}
					})
				})
			})
		
			// 当页面有ajax请求的时候触发 
			$(document).on('ajaxStart', function () {
				NProgress.start();
			})

			// 当页面有ajax请求完成时候触发 
			$(document).on('ajaxComplete', function () {
				NProgress.done();
			})
		</script>
	</body>
</html>
